<template>
 <div class="user">
    <h2>修改头像</h2>
    <el-alert
    title="关于上传头像"
    type="success"
    description="选择头像后,即可完成头像的自动上传"
    show-icon
  >
  </el-alert>
    <el-upload
      class="avatar-uploader"
      :action="baseURL+'/admin/adminInfo/altPhone'"   
      :show-file-list="false"              
      :on-success="handleAvatarSuccess"   
      :with-credentials="true"            
      :before-upload="beforeAvatarUpload"  
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
 
<script>
import {mapMutations} from "vuex"
export default {
  name: 'AltPhone',
  data(){
    return{
       imageUrl: ''   // 缩略图地址
    }
  },
  methods:{
    ...mapMutations(['updateAdminInfo']),
    // 头像上传之的操作
    beforeAvatarUpload(file) {
      const isJPG = /^image\/(jpeg|png)$/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    // 上传成功之后的操作
    handleAvatarSuccess(res,file){
      if(res.code){
        return this.$message.warning(res.mes)
      }
      // 显示缩略图
      this.imageUrl = URL.createObjectURL(file.raw)
      // 更新vuex
      this.updateAdminInfo(res.data)
      // 提示
      this.$message.success(res.mes)
    }
  }
}
</script>

<style scoped lang='less'>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #bababb;
    margin-top: 20px;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.user{
  margin-bottom: 45px;
  h2{
    width: 100%;
    height: 50px;
    line-height: 40px;
    font-size: 20px;
    color: purple;
    box-sizing: border-box;
    border-bottom: 1px solid #eee;
  }
  #name{
    background-color: rgb(230, 229, 229);
    color: red;
    padding: 5px 10px;
  }
}
</style>